import 'package:flutter_enjoy_plus/constants/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TokenManager {
  String? _token;
  String? _refreshToken;
//初始化token
  init() async {
    var instance = await _getInstance();
    _token = instance.getString(GlobalVariable.TOKEN_KEY) ?? '';
    _refreshToken = instance.getString(GlobalVariable.REFRESH_TOKEN_KEY) ?? '';
  }

  //获取SharedPreferences实例
  Future<SharedPreferences> _getInstance() {
    return SharedPreferences.getInstance();
  }

  //设置token
  setToken(String token, {String? refreshToken}) async {
    var instance = await _getInstance();
    _token = token;
    instance.setString(GlobalVariable.TOKEN_KEY, token);
    if (refreshToken != null) {
      instance.setString(GlobalVariable.REFRESH_TOKEN_KEY, refreshToken);
    }
    _refreshToken = refreshToken;
  }

  //获取token
  getToken() {
    return _token ?? '';
  }

  getRefreshToken() {
    return _refreshToken ?? '';
  }

  //删除token
  removeToken() async {
    var instance = await _getInstance();
    _token = null;
    _refreshToken = null;
    instance.remove(GlobalVariable.TOKEN_KEY);
    instance.remove(GlobalVariable.REFRESH_TOKEN_KEY);
  }
}

final tokenManager = TokenManager();
